package com.itlaobing.demo.servlet;

import com.itlaobing.demo.model.UserinfoModel;
import com.itlaobing.demo.util.DBHelper;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;

/**
 * @Classname UpdateImgServlet
 * @Description TODO()
 * @Date 2020/11/10 0010 17:02
 * @Author by Administrator
 * @Version v1.0
 */
@WebServlet("/header")
@MultipartConfig(maxFileSize=1024 * 1024 * 10) // 支持文件上传
public class HeaderServlet extends HttpServlet {

    private String types = "image/png;image/jpg;image/jpeg";

    /**
     * 处理 url 为  xx/header 的 get 请求
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 到修改头像页面
        req.getRequestDispatcher("WEB-INF/pages/sys/header.jsp").forward(req, resp);
    }

    /**
     * 处理 url 为  xx/header 的 post 请求
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 上传头像后保存
        Part part = req.getPart("file");

        if (!(part == null || part.getSize() == 0)){
            // 验证文件格式
            String type = part.getContentType();
            // 文件格式有问题
            if (!types.contains(type)){
                req.setAttribute("msg", "文件格式有误，请检查后重新上传");
                req.getRequestDispatcher("WEB-INF/pages/sys/header.jsp").forward(req, resp);
                return;
            }

            // 保存文件，String fileName = part.getName();
            String dir =  LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            String localPath = "D://temp//header" + File.separator + dir;
            File file = new File(localPath);
            if (!file.exists()){
                file.mkdirs();
            }
            // 1.png
            String fileName = part.getSubmittedFileName();
            // 保存时文件名字  2020-11-10/1324655561.png
            String saveName = System.currentTimeMillis() + fileName;
            // 写文件
            part.write(localPath + File.separator + saveName);

            // 访问路径  file?name=2020-11-10/1324655561.png
            // 找文件 D://temp//header//2020-11-10//1324655561.png
            String path = "file?name=" + dir + "/" +  saveName;

            // 获取当前用户信息
            HttpSession session = req.getSession();
            UserinfoModel model = (UserinfoModel) session.getAttribute("user");
            // 更新头像信息
            DBHelper db = new DBHelper();

            String sql = "update userinfo set imgUrl = ? where id = ?";

            int row = db.executeUpdate(sql, path, model.getId());

            if (row > 0){
                model.setImgUrl(path);
                //上传成功
                resp.sendRedirect("index");
            }else{
                req.setAttribute("msg" , "上传失败，请重试");
                req.getRequestDispatcher("WEB-INF/pages/sys/header.jsp").forward(req, resp);
            }
        }else {
            resp.sendRedirect("header");
        }

    }

}
